#!/usr/bin/env python
#-*- coding: utf-8 -*-

# Author: Edward Roualdes
#         [2012.11.05]
#         University of Kentucky

import os
import re
import subprocess
import sys
from multiprocessing import Pool


def files2align(outputDir):
    """creates iterable of files in outputDir with extension .fna"""
    l = []
    pat = re.compile(".*\\.fna$")
    # scan files in directory outputDir
    for root, dirs, files in os.walk(outputDir):
        for fname in filter(pat.match, files): # filter based on extension
            f = os.path.join(root, fname)
            l.append(f)
    return l

def aligner(f, prog, alignerPath):
    """performs alignment on file f using alignment prog located at alignerPath."""
    # align reads in file
    if prog == "muscle":
        subprocess.call([alignerPath, "-quiet", "-in", f, \
                                     "-out", f + ".aligned"])
    elif prog == "mafft":
        faFile = open(f + ".aligned", "w")
        subprocess.call([alignerPath, "--auto", "--quiet", f], \
                            stdout=faFile)
        faFile.close()
    else:
        print prog, ": unknown aligner program."
        sys.exit()
                

if __name__ == "__main__":

    i = sys.argv[1]             # outputDir
    p = sys.argv[2]             # prog
    apath = sys.argv[3]         # alignerPath

    def alignTool(x):
        return aligner(x, p, apath)

    l = files2align(i)
    p = Pool()
    p.map(alignTool, l)
    

    
            
    
    
